/*
 * @(#)MaintFormPageAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSubmissionHtml;
import com.dcivision.form.bean.MtmFormPageFormSection;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.form.dao.FormSubmissionHtmlDAObject;
import com.dcivision.form.dao.MtmFormPageFormSectionDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintFormPageAction.java

  This class is for maint user record.

    @author          Scott Tong
    @company         DCIVision Limited
    @creation date   2/1/2004
    @version         $Revision: 1.21 $
*/

public class MaintFormPageAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.21 $";

  protected String listName = "";
  public MaintFormPageAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormPageDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    MaintFormPageForm maintFormPageForm = (MaintFormPageForm)form;
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    
    int formPageNo = 0; // formPageNo is formPageList SeqNO,not formPage.getPageNo .
    String formRecordID = request.getParameter("formRecordID");
    Integer formPageID = null;
    if(!Utility.isEmpty(request.getParameter("formPageNo"))){
    	formPageNo = Integer.parseInt(request.getParameter("formPageNo"));
    }
    
    FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
    List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(formRecordID),new Integer(0));
    
    FormPage tempFormPage = (FormPage)formPageList.get(formPageNo);
    formPageID = tempFormPage.getID();
    
    if(request.getParameter("preview")!=null){
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
     if (request.getParameter("preview").equals("T")){
       request.setAttribute("preview", "T");
       selectRecord(mapping, (AbstractActionForm) form, request, response);
       try{
	       FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(this.getSessionContainer(request), this.getConnection(request));
	       FormSubmissionHtml formSubmissionHtml = (FormSubmissionHtml)formSubmissionHtmlDAO.getByRecordIDPageID(new Integer(formRecordID),formPageID);
	       return mapping.findForward(GlobalConstant.NAV_MODE_CHANGE);
       }catch (ApplicationException appEx) {
	       	  if(appEx.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
	       	  	return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
	       	  }
	       return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
       }
     }else{
       request.setAttribute("preview", "T");
       selectRecord(mapping, (AbstractActionForm) form, request, response);
       try{
	       FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(this.getSessionContainer(request), this.getConnection(request));
	       FormSubmissionHtml formSubmissionHtml = (FormSubmissionHtml)formSubmissionHtmlDAO.getByRecordIDPageID(new Integer(formRecordID),formPageID);
	       return mapping.findForward(maintFormPageForm.NAV_MODE_EXPORT_DB);
       }catch (ApplicationException appEx) {
	       	  if(appEx.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
	       	   return mapping.findForward(maintFormPageForm.NAV_MODE_EXPORT);
	       	  }
	       	 return mapping.findForward(maintFormPageForm.NAV_MODE_EXPORT);
       }
     }
    } else {
    	
      return super.execute(mapping, form, request, response);
    }


 }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
   
  	if(request.getParameter("preview")!=null){
  		try {
  			MaintFormPageForm formPageForm = (MaintFormPageForm)form;
  			FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
  			FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request)); 			
  			int pageNo = 0;			
  			if(!Utility.isEmpty(request.getParameter("formPageNo")) && !"null".equals(request.getParameter("formPageNo")) ){
  				pageNo = Integer.parseInt(request.getParameter("formPageNo"));
  			} 			
  			Integer formRecordID = TextUtility.parseIntegerObj(formPageForm.getFormRecordID());
  			FormRecord formRecord = (FormRecord)formRecordDAO.getObjectByID(formRecordID);
  			request.setAttribute("formRecord",formRecord);  			
  			FormPage formPage = null;
  			List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(formRecordID,new Integer(0));
  			if (!Utility.isEmpty(formPageList) ){
  				formPage = (FormPage)formPageList.get(pageNo);	     	
  				request.setAttribute("formPageList", formPage);
  				formPageForm.setFormData(formPage);
  			} 			
  			request.setAttribute("formPageListName",formPageList);
  			
  			
  		} catch (ApplicationException appEx) {
  			throw appEx;
  		} catch (Exception e) {
  			log.error(e, e);
  			throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
  		} finally {}
  	}else{
  		super.selectRecord(mapping, form, request, response);
  	}
	 }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form,HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintFormPageForm formPageForm = (MaintFormPageForm)form;
    String fontStyle="";
    if (request.getParameter("fontStyleBold") != null)
      fontStyle += "B";
    if (request.getParameter("fontStyleUnderline") != null)
      fontStyle += "U";
    if (request.getParameter("fontStyleItalic") != null)
      fontStyle += "I";
    formPageForm.setTitleFontStyle(fontStyle);
    formPageForm.setPageNo("0");
    
    super.insertRecord(mapping, formPageForm, request, response);

  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	MaintFormPageForm formPageForm = (MaintFormPageForm)form;
    String fontStyle = "";
    if (request.getParameter("fontStyleBold") != null)
      fontStyle += "B";
    if (request.getParameter("fontStyleUnderline") != null)
      fontStyle += "U";
    if (request.getParameter("fontStyleItalic") != null)
      fontStyle += "I";
    formPageForm.setTitleFontStyle(fontStyle);
    super.updateRecord(mapping, formPageForm, request, response);

  }
  
  public void deleteAllRecord(ActionMapping mapping,
	      AbstractActionForm form,
	      HttpServletRequest request,
	      HttpServletResponse response) throws ApplicationException {
  		MaintFormPageForm formPageForm = (MaintFormPageForm)form;  
		  String formRecordID = "";
  		String formPageID = "";
  		int delPageSeq = 0;
		  int delSectionID = 0;
		  Integer preSectionID = new Integer(-1);
		  formRecordID = formPageForm.getFormRecordID();
		  formPageID = formPageForm.getID();
					  
		  FormPageDAObject formPageDAO = new FormPageDAObject(
		  		this.getSessionContainer(request),this.getConnection(request));			  
		  MtmFormPageFormSection mtmFormPageFormSection = new MtmFormPageFormSection();
		  MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO =
		  new MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
		                      this.getConnection(request));
		  MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =
		  new MtmFormSectionFormElementDAObject(this.getSessionContainer(request),
		                         this.getConnection(request));
		  FormSectionDAObject formSectionDAO = new FormSectionDAObject(
		  this.getSessionContainer(request), this.getConnection(request));
		  FormElementDAObject formElementDAO = new FormElementDAObject(
			this.getSessionContainer(request), this.getConnection(request));
		  
		  // Get all page of Record
		  List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));
		  for (int nn = formPageList.size()-1; nn >= 0; nn--){
		  	if (nn < 0){break;}
			  FormPage formPage = (FormPage)formPageList.get(nn);
			  // Get the seqNo of deleted page
			  delPageSeq = formPage.getPageNo().intValue();
			  // Begin delet the Page of Form Record.
			  if (delPageSeq != 0){
			  		
			  	//   Get all sections of page [formPageID]
				  List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO.
				  getListByPageID(new Integer(formPageID));
				  //   Get the previous section at the deleted section
				  for (int i = mtmFormPageFormSectionList.size()-1; i >= 0;i--) {
					  if (i <0) { break;}
					  MtmFormPageFormSection tmpMtmFormPageFormSection =
					  (MtmFormPageFormSection)mtmFormPageFormSectionList.get(i);				  
					  delSectionID = tmpMtmFormPageFormSection.getSectionID().intValue();
					  
					
					  //   Delete all Elements's in FORM_ELEMENT table.
					  List mtmFormSectionFormElementList = mtmFormSectionFormElementDAO.
					  getListBySectionID(new Integer(delSectionID));
					  for (int k =0; k < mtmFormSectionFormElementList.size(); k++){
					  	FormElement formElement =(FormElement) mtmFormSectionFormElementList.get(k); 
					  	formElementDAO.deleteObjectByID(formElement.getID());
					  }

					  //   Delete all Elements's in MTM_FORM_SECTION_FORM_ELEMENT table
					  List delElementList = mtmFormSectionFormElementDAO.getListBySectionID(
					  new Integer(delSectionID));
						  for (int j = 0; j < delElementList.size(); j++) {
							  MtmFormSectionFormElement tmpUpdateMtmSectionElement =
							  (MtmFormSectionFormElement)delElementList.get(j);
							  mtmFormSectionFormElementDAO.deleteObjectByID(tmpUpdateMtmSectionElement.getID());
							  
						  }
					 
				  }
				  //   Delete section in MTM_FORM_PAGE_FORM_SECTION table
				  mtmFormPageFormSectionDAO.deleteObject(mtmFormPageFormSection);
				
				  //   Delete section in FORM_SECTION table
				  formSectionDAO.deleteObjectByID(new Integer(delSectionID));
				  formPageDAO.deleteObjectByID(formPage.getID());
		  }
			  //End delete the page of Form Record.
	  }
  }
  
  public void deleteRecord(ActionMapping mapping,
      AbstractActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) throws ApplicationException {
		MaintFormPageForm formPageForm = (MaintFormPageForm)form;  
	  String formRecordID = "";
		String delPageID = "";
		Integer delPageSeq;
	  int preSectionSeq = 0; 
	  Integer prePageID = new Integer(-1);
	  formRecordID = formPageForm.getFormRecordID();
	  delPageID = formPageForm.getID();
	  delPageSeq =new Integer(formPageForm.getPageNo());
				  
	  FormPageDAObject formPageDAO = new FormPageDAObject(
	  		this.getSessionContainer(request),this.getConnection(request));			  
	  MtmFormPageFormSection mtmFormPageFormSection = new MtmFormPageFormSection();
	  MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO =
	  new MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
	                      this.getConnection(request));
	  
	  // Get all page of Record
	  List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));
	  for (int nn = formPageList.size()-1; nn >= 0; nn--){
	  	if (nn < 0){break;}
		  FormPage formPage = (FormPage)formPageList.get(nn);  
		  // Get the seqNo of deleted page.
		  
		  if (!Utility.isEmpty(delPageSeq)){	  	
		  	if (formPage.getPageNo().intValue() < delPageSeq.intValue()) {
				  prePageID = formPage.getID();
				  //Get last Section SeqNO of the pre Page.
				  List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO.getListByPageID(prePageID);
				  MtmFormPageFormSection lastFormPageFormSection = 
				  	(MtmFormPageFormSection)mtmFormPageFormSectionList.get(mtmFormPageFormSectionList.size()-1);
			  
				  Integer lastSectionSeq = lastFormPageFormSection.getSectionSeq();
	
	        // Update all Elements's seqNo of pre section
	        List delSectionList = mtmFormPageFormSectionDAO.getListByPageID(
	            new Integer(delPageID));
	        for (int j = 0; j < delSectionList.size(); j++) {
	          MtmFormPageFormSection tmpUpdateMtmPageSection =
	              (MtmFormPageFormSection)delSectionList.get(j);
	          tmpUpdateMtmPageSection.setSectionSeq(
	              new Integer(lastSectionSeq.intValue()+j+1));
	          tmpUpdateMtmPageSection.setPageID(prePageID);
	          mtmFormPageFormSectionDAO.updateObject(tmpUpdateMtmPageSection);

	        }
			  }	
		  }
	  }
//  Delete page in FORM_PAGE table
	  formPageDAO.deleteObjectByID(new Integer(delPageID));			  
  }
}